import React, { useState } from 'react'
import { Space, Button, Modal } from 'antd'
import CanCelModal from './components/CanCelModal'
import OperateConfirmModal from './components/OperateConfirmModal'
import { ExclamationCircleOutlined } from '@ant-design/icons'

const { confirm } = Modal

// 获取文书列表
function getDocList (list) {
  return list.filter(li => li.type === '文书')
}

// 填充默认文书值到表单
function fillDocToVars (formRef, list) {
  const m = {}
  const c = formRef.current
  list.forEach(li => {
    if (li.value) {
      m[li.key] = li.value
    }
  })
  if (c) {
    const { vars } = c.getFieldsValue(['vars'])
    formRef.current.setFieldsValue({ vars: { ...vars, ...m } })
  }
}

// 完成处理方法
function finishHandle (d = {}, formRef, action, docList, setVisible, callBack) {
  if (d.defaultDocList && d.defaultDocList instanceof Array && d.defaultDocList.length) {
    d.docList = [...d.defaultDocList, ...d.docList]
    delete d.defaultDocList
  }
  const hasLevel = Object.prototype.hasOwnProperty.call(d, 'level')
  const hasDoc = Object.prototype.hasOwnProperty.call(d, 'docList')
  if (hasLevel) {
    action.level = d.level
  }
  if (hasDoc) {
    fillSelectedDocToVars(formRef, d)
  } else if (docList.length > 0) {
    fillDocToVars(formRef, docList)
  }
  if (d.remark) {
    formRef.current.setFieldsValue({ remark: d.remark })
  }
  setVisible(false)
  callBack(action)
}

// 填充选中的文书到vars中
function fillSelectedDocToVars (formRef, d) {
  const c = formRef.current
  const params = c.getFieldsValue()
  const vars = params.vars
  const varsKeys = Object.keys(vars)
  varsKeys.forEach(v => {
    if (d.docList.indexOf(v) !== -1) {
      vars[v] = v
    }
  })
  c.setFieldsValue({ vars })
}

// 渲染呈批取消按钮
function renderCancelApproveBtn (instance, showFn) {
  const h = instance.history || []
  if (h.length === 0) {
    return (
      <Button onClick={showFn}>删除呈批</Button>
    )
  }
}

// 二次确认弹框
function showConfirm (action, callback) {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: (
      <div>
        <div>{action.alertmsg}</div>
        {action.employees ? <div>下一步操作者：{action.employees}</div> : null}
      </div>

    ),
    onOk: callback
  })
}

function Main ({ loading, data, instance, refreshApprove, action, setAction, formRef, callBack }) {
  const [cancelVisible, setCancelVisible] = useState(false)
  const [visible, setVisible] = useState(false)
  const docList = getDocList(instance.currentStep.vars)
  return (
    <div>
      <OperateConfirmModal visible={visible} onHide={() => { setVisible(false); setAction(null) }} docList={docList} action={action} onFinish={d => finishHandle(d, formRef, action, docList, setVisible, callBack)} />
      <CanCelModal visible={cancelVisible} instance={instance} hide={() => { setCancelVisible(false); setAction(null) }} refreshApprove={refreshApprove} />
      <Space>
        {renderCancelApproveBtn(instance, () => setCancelVisible(true))}
        {
          (data.actions || []).map((li, i) => {
            let type = 'primary'
            if (['disagree', 'normal', 'cancel'].indexOf(li.opt_add) !== -1) {
              type = ''
            }
            const defaultHandle = () => {
              fillDocToVars(formRef, docList)
              callBack(li)
            }
            let handle = () => defaultHandle()
            const hasLevel = Object.prototype.hasOwnProperty.call(li, 'level')
            const hasUnSelectDoc = docList.length > 0 && docList.some(li => !li.value || li.value === 'select')
            if (hasLevel || hasUnSelectDoc || li.opt_add === 'cancel') {
              handle = () => {
                setVisible(true)
                setAction(li)
              }
            } else if (li.alertmsg) {
              handle = () => {
                showConfirm(li, defaultHandle)
              }
            }
            return (
              <Button key={li.id} type={type} disabled={loading} onClick={handle}>
                {li.name}
              </Button>
            )
          })
        }
      </Space>
    </div>
  )
}

export default Main
